package org.linlinjava.litemall.admin.service.order_manage;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang.StringUtils;
import org.linlinjava.litemall.admin.form.StoreStaffAddForm;
import org.linlinjava.litemall.admin.vo.wechat.GroupMessage;
import org.linlinjava.litemall.admin.vo.wechat.UpdateGroupMessage;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.config.CenterServerAddress;
import org.linlinjava.litemall.db.config.ServerAddress;
import org.linlinjava.litemall.db.dao.*;
import org.linlinjava.litemall.db.dao.order_manage.BackendStoreStaffMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.AgedmallUserInfoService;
import org.linlinjava.litemall.db.util.EnumUserRegisterSource;
import org.linlinjava.litemall.db.util.OrderUtil;
import org.linlinjava.litemall.db.vo.order_manage.BackBusiStaffStoreVo;
import org.linlinjava.litemall.db.vo.order_manage.BackBusiStaffVo;
import org.linlinjava.litemall.db.vo.order_manage.BackendStoreStaffOrderGoodsListVo;
import org.linlinjava.litemall.db.vo.order_manage.BackendStoreStaffOrderListVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class AgedmallShopStaffService {

    @Resource
    private LitemallUserMapper litemallUserMapper;
    @Resource
    private AgedmallUserInfoMapper agedmallUserInfoMapper;
    @Resource
    private AgedmallDeliveryManInfoMapper agedmallDeliveryManInfoMapper;
    @Resource
    private BackendStoreStaffMapper backendStoreStaffMapper;
    @Autowired
    private AgedmallUserInfoService agedmallUserInfoService;
    @Resource
    private AgedmallStoreMapper agedmallStoreMapper;
    @Resource
    private AgedmallBusiAdminMapper agedmallBusiAdminMapper;
    @Resource
    private AgedmallWechatGroupNumberMapper agedmallWechatGroupNumberMapper;
    @Resource
    private AgedmallWechatGroupMapper agedmallWechatGroupMapper;
    @Resource
    private ServerAddress serverAddress;


    public Object getResultMessage(String result){
        JSONObject jsonObject = JSON.parseObject(result);
        String msg =(String)jsonObject.get("errmsg") ;
        int code =(int)jsonObject.get("errcode") ;
        if(code!=0){
            return ResponseUtil.fail(code,msg);
        }
        else {
            return ResponseUtil.ok();
        }
    }

    public int getResultCode(String result){
        JSONObject jsonObject = JSON.parseObject(result);
        return (int)jsonObject.get("code") ;
    }

    public String getResultData(String result){
        JSONObject jsonObject = JSON.parseObject(result);
        return (String) jsonObject.get("data") ;
    }

    public Object list(Integer busiId, String keySearch, Integer storeId,Integer page, Integer limit){
        PageHelper.startPage(page, limit);
        List<BackBusiStaffVo> list = backendStoreStaffMapper.list(busiId, keySearch, storeId);
        for (BackBusiStaffVo backBusiStaffVo : list) {
            List<BackBusiStaffStoreVo> backBusiStaffStoreVos = backendStoreStaffMapper.storeList(backBusiStaffVo.getId());
            List<AgedmallCloudHouse> agedmallCloudHouses = backendStoreStaffMapper.cloudList(backBusiStaffVo.getId());
            backBusiStaffVo.setStoreInfo(backBusiStaffStoreVos);
            backBusiStaffVo.setAgedmallCloudHouses(agedmallCloudHouses);
        }
        return ResponseUtil.okList(list);
    }

    @Transactional
    public Object add(Integer busiId, StoreStaffAddForm storeStaffAddForm){
        // 查询员工是否存在 同一店铺手机号确定唯一用户
        AgedmallDeliveryManInfoExample agedmallDeliveryManInfoExample = new AgedmallDeliveryManInfoExample();
        agedmallDeliveryManInfoExample.createCriteria().andDeletedEqualTo(false)
                .andPhoneEqualTo(storeStaffAddForm.getContactInformation());
        AgedmallDeliveryManInfo info = agedmallDeliveryManInfoMapper.selectOneByExample(agedmallDeliveryManInfoExample);
        if (null != info) {
            return ResponseUtil.fail("用户已存在");
        }
        info = new AgedmallDeliveryManInfo();
        if(StrUtil.isNotBlank(storeStaffAddForm.getCardNumber())){
            AgedmallDeliveryManInfoExample icNumExample = new AgedmallDeliveryManInfoExample();
            icNumExample.createCriteria().andDeletedEqualTo(false)
                    .andIcNumEqualTo(storeStaffAddForm.getCardNumber());
            AgedmallDeliveryManInfo isNumExist = agedmallDeliveryManInfoMapper.selectOneByExample(icNumExample);
            if(ObjectUtil.isNotNull(isNumExist)){
                return ResponseUtil.fail("ic卡编号已存在");
            }

            String rfidResult=HttpRequest.post(serverAddress.getCenter()+"admin_api/getRfidByIcCardNumber/"+storeStaffAddForm.getCardNumber())
                    //头信息，多个头信息多次调用此方法即可
                    .header(CenterServerAddress.KEY_HEADER_STRING,CenterServerAddress.KEY_SECUREUTIL_MD5)
                    .timeout(50000)//超时，毫秒
                    .execute().body();
            int resultCode = getResultCode(rfidResult);
            if(resultCode!=0){
                return getResultMessage(rfidResult);
            }
            if(StringUtils.isNotBlank(getResultData(rfidResult))){
            info.setIcCard(getResultData(rfidResult));
            }
        }

        info.setBusiId(busiId);
        info.setStoreId(storeStaffAddForm.getStoreId());
        info.setCloudId(storeStaffAddForm.getCloudId());
        info.setUsername(storeStaffAddForm.getStaffName());
        info.setPhone(storeStaffAddForm.getContactInformation());
        info.setHasSystem(storeStaffAddForm.getStaffType());
        info.setIcNum(storeStaffAddForm.getCardNumber());
        info.setRoles(storeStaffAddForm.getStaffRole());
        info.setWechatId(storeStaffAddForm.getStaffWechatName());
        info.setAddTime(LocalDateTime.now());
        info.setUpdateTime(LocalDateTime.now());
        info.setDeleted(false);

        //增加群相关
        //判断群人数
        String[] members=storeStaffAddForm.getGroupMembers().split(",");
        List<String> membersList=new ArrayList<>();
        Collections.addAll(membersList,members);
        boolean isExist=membersList.contains(storeStaffAddForm.getGroupManager());
        if(!isExist){
            membersList.add(storeStaffAddForm.getGroupManager());
        }
        if(membersList.size()<2){
            return ResponseUtil.fail(1200,"群成员人数必须大于2个");
        }
        AgedmallWechatGroupNumber groupNumber=new AgedmallWechatGroupNumber();
        agedmallWechatGroupNumberMapper.insert(groupNumber);
        AgedmallWechatGroup wechatGroup=new AgedmallWechatGroup();
        String groupName=storeStaffAddForm.getGroupName().length()>51?
                storeStaffAddForm.getGroupName().substring(0,51):storeStaffAddForm.getGroupName();
        wechatGroup.setGroupName(groupName);
        wechatGroup.setGroupManager(storeStaffAddForm.getGroupManager());
        wechatGroup.setGroupMembers(storeStaffAddForm.getGroupMembers());
        wechatGroup.setGroupId(groupNumber.getId());
        wechatGroup.setAddTime(LocalDateTime.now());
        agedmallWechatGroupMapper.insertSelective(wechatGroup);
        info.setWechatGroupId(wechatGroup.getId());

        // 有运维后台 要注册用户
        if (1 == storeStaffAddForm.getStaffType()) {
            // 查询用户表， 有的话 只要关联门店
            LitemallUserExample litemallUserExample = new LitemallUserExample();
            litemallUserExample.createCriteria().andDeletedEqualTo(false)
                    .andMobileEqualTo(storeStaffAddForm.getContactInformation());
            LitemallUser user = litemallUserMapper.selectOneByExample(litemallUserExample);
            if (null == user) {
                user = new LitemallUser();
                user.setUsername(storeStaffAddForm.getContactInformation());
                user.setNickname(storeStaffAddForm.getStaffName());
                user.setMobile(storeStaffAddForm.getContactInformation());
                user.setGender((byte) 0);
                user.setUserLevel((byte) 0);
                user.setStatus((byte) 0);
                user.setCreateSource(EnumUserRegisterSource.SYSTEM.getSource());
                user.setAddTime(LocalDateTime.now());
                user.setUpdateTime(LocalDateTime.now());
                user.setDeleted(false);
                litemallUserMapper.insertSelective(user);
                agedmallUserInfoService.add(user.getId());
            }
            info.setUserId(user.getId().longValue());
        }

        agedmallDeliveryManInfoMapper.insertSelective(info);
        GroupMessage groupMessage=new GroupMessage();
        groupMessage.setName(groupName);
        groupMessage.setManagerName(storeStaffAddForm.getGroupManager());
        groupMessage.setUserList(membersList);
        groupMessage.setChatId(wechatGroup.getGroupId().toString());
        String result=HttpRequest.post(serverAddress.getCorp()+"message/createGroupChat")
                .body(JSON.toJSONString(groupMessage))
                .timeout(50000)
                .execute().body();
        return getResultMessage(result);
    }

    @Transactional
    public Object update(Integer busiId, StoreStaffAddForm storeStaffAddForm){
        AgedmallDeliveryManInfo info = agedmallDeliveryManInfoMapper.selectByPrimaryKey(storeStaffAddForm.getId());
        if (null == info) {
            return ResponseUtil.badArgumentValue();
        }
        // 查询员工是否存在 同一店铺手机号确定唯一用户
        AgedmallDeliveryManInfoExample agedmallDeliveryManInfoExample = new AgedmallDeliveryManInfoExample();
        agedmallDeliveryManInfoExample.createCriteria().andDeletedEqualTo(false)
                .andIdNotEqualTo(info.getId())
                .andPhoneEqualTo(storeStaffAddForm.getContactInformation());
        AgedmallDeliveryManInfo deliveryManInfo = agedmallDeliveryManInfoMapper.selectOneByExample(agedmallDeliveryManInfoExample);
        if (null != deliveryManInfo) {
            return ResponseUtil.fail("用户已存在");
        }
        if(StrUtil.isNotBlank(storeStaffAddForm.getCardNumber())){
            AgedmallDeliveryManInfoExample icNumExample = new AgedmallDeliveryManInfoExample();
            icNumExample.createCriteria().andDeletedEqualTo(false)
                    .andIcNumEqualTo(storeStaffAddForm.getCardNumber());
            AgedmallDeliveryManInfo isNumExist = agedmallDeliveryManInfoMapper.selectOneByExample(icNumExample);
            if(ObjectUtil.isNotNull(isNumExist)&&!info.getIcNum().equals(storeStaffAddForm.getCardNumber())){
                return ResponseUtil.fail("ic卡编号已存在");
            }
            String rfidResult=HttpRequest.post(serverAddress.getCenter()+"admin_api/getRfidByIcCardNumber/"+storeStaffAddForm.getCardNumber())
                    //头信息，多个头信息多次调用此方法即可
                    .header(CenterServerAddress.KEY_HEADER_STRING,CenterServerAddress.KEY_SECUREUTIL_MD5)
                    .timeout(50000)//超时，毫秒
                    .execute().body();
            int resultCode = getResultCode(rfidResult);
            if(resultCode!=0){
                return getResultMessage(rfidResult);
            }
            info.setIcCard(getResultData(rfidResult));
        }



        info.setStoreId(storeStaffAddForm.getStoreId());
        info.setCloudId(storeStaffAddForm.getCloudId());
        info.setUsername(storeStaffAddForm.getStaffName());
        info.setPhone(storeStaffAddForm.getContactInformation());
        info.setHasSystem(storeStaffAddForm.getStaffType());
        info.setIcNum(storeStaffAddForm.getCardNumber());
        info.setRoles(storeStaffAddForm.getStaffRole());
        info.setUpdateTime(LocalDateTime.now());
        info.setWechatId(storeStaffAddForm.getStaffWechatName());

        //修改群相关
        AgedmallWechatGroup wechatGroup = agedmallWechatGroupMapper.selectByPrimaryKey(info.getWechatGroupId());
        //前端的成员
        String[] nowMembers=storeStaffAddForm.getGroupMembers().split(",");
        List<String> nowMembersList=new ArrayList<>();
        Collections.addAll(nowMembersList,nowMembers);
        //原来的成员
        String[] oldMembers=wechatGroup.getGroupMembers().split(",");
        List<String> oldMembersList=new ArrayList<>();
        Collections.addAll(oldMembersList,oldMembers);
        List<String> addMembers=new ArrayList<>();;
        List<String> delMembers=new ArrayList<>();;
        //需要删除的成员
        for (int i = 0; i < oldMembersList.size(); i++) {
              if(!nowMembersList.contains(oldMembersList.get(i))){
                  delMembers.add(oldMembersList.get(i));
              }
        }
        //需要新增的成员
        for (int i = 0; i < nowMembersList.size(); i++) {
            if(!oldMembersList.contains(nowMembersList.get(i))){
                addMembers.add(nowMembersList.get(i));
            }
        }
        String groupName=storeStaffAddForm.getGroupName().length()>51?
                storeStaffAddForm.getGroupName().substring(0,51):storeStaffAddForm.getGroupName();
        wechatGroup.setGroupName(groupName);
        wechatGroup.setGroupManager(storeStaffAddForm.getGroupManager());
        wechatGroup.setGroupMembers(storeStaffAddForm.getGroupMembers());
        agedmallWechatGroupMapper.updateByPrimaryKeySelective(wechatGroup);



        if (1 == storeStaffAddForm.getStaffType()) {
            // 查询用户表， 有的话 只要关联门店
            LitemallUserExample litemallUserExample = new LitemallUserExample();
            litemallUserExample.createCriteria().andDeletedEqualTo(false)
                    .andMobileEqualTo(storeStaffAddForm.getContactInformation());
            LitemallUser user = litemallUserMapper.selectOneByExample(litemallUserExample);
            if (null == user) {
                user = new LitemallUser();
                user.setUsername(storeStaffAddForm.getContactInformation());
                user.setNickname(storeStaffAddForm.getStaffName());
                user.setMobile(storeStaffAddForm.getContactInformation());
                user.setGender((byte) 0);
                user.setUserLevel((byte) 0);
                user.setStatus((byte) 0);
                user.setCreateSource(EnumUserRegisterSource.SYSTEM.getSource());
                user.setAddTime(LocalDateTime.now());
                user.setUpdateTime(LocalDateTime.now());
                user.setDeleted(false);
                litemallUserMapper.insertSelective(user);
                agedmallUserInfoService.add(user.getId());
            }
            info.setUserId(user.getId().longValue());
        } else {
            info.setUserId(null);
        }

        agedmallDeliveryManInfoMapper.updateByPrimaryKey(info);
        //TODO 调用接口修改群聊
        UpdateGroupMessage updateGroupMessage=new UpdateGroupMessage();
        updateGroupMessage.setChatId(wechatGroup.getGroupId().toString());
        updateGroupMessage.setName(wechatGroup.getGroupName());
        updateGroupMessage.setOwner(wechatGroup.getGroupManager());
        updateGroupMessage.setAddUserList(addMembers);
        updateGroupMessage.setDelUserList(delMembers);
        String result=HttpRequest.post(serverAddress.getCorp()+"message/updateGroupChat")
                .body(JSON.toJSONString(updateGroupMessage))
                .timeout(50000)
                .execute().body();
        return getResultMessage(result);
    }

    public Object del(Integer staffId){
        AgedmallDeliveryManInfo info = agedmallDeliveryManInfoMapper.selectByPrimaryKey(staffId);
        if (null == info) {
            return ResponseUtil.badArgumentValue();
        }

        AgedmallStoreExample agedmallStoreExample = new AgedmallStoreExample();
        agedmallStoreExample.createCriteria().andDeletedEqualTo((byte)0)
                .andBusiIdEqualTo(info.getBusiId())
                .andPhoneEqualTo(info.getPhone());
        AgedmallStore store = agedmallStoreMapper.selectOneByExample(agedmallStoreExample);
        if (null != store) {
            return ResponseUtil.fail("该员工为门店管理员，请在门店详情--编辑门店中更换门店管理员后在删除。");
        }
        if (StringUtils.isNotEmpty(info.getStoreId())) {
            return ResponseUtil.fail("该员工已关联门店，请在门店详情--员工管理中删除。");
        }
        agedmallDeliveryManInfoMapper.logicalDeleteByPrimaryKey(staffId);
        return ResponseUtil.ok();
    }

    public Object detailOrderList(Integer busiId, Integer staffId, Integer state, Integer page, Integer limit){
        PageHelper.startPage(page, limit);
        List<BackendStoreStaffOrderListVo> list = backendStoreStaffMapper.staffOrderList(busiId, staffId, state);
        for (BackendStoreStaffOrderListVo backendStoreStaffOrderListVo : list) {
            List<BackendStoreStaffOrderGoodsListVo> goodsListVos = backendStoreStaffMapper.staffOrderGoodsList(busiId, staffId, state, backendStoreStaffOrderListVo.getOrderId());
            goodsListVos.stream().forEach(p -> p.setOrderStatus(OrderUtil.backendShowType(p.getOrderStatus().shortValue())));
            backendStoreStaffOrderListVo.setGoodsList(goodsListVos);
        }
        return ResponseUtil.okList(list);
    }
}
